$(document).ready(function(){
	// 筛选条件下拉框初始化
	initFilters();

	// 对话框初始化
	initAidDialog();
	
	// 切换项目、学期按钮
	$("#bthSwitchProjectPhase").click(function(){
		popupProjectPhaseDialog();
	});
	
	// 筛选按钮
	$("#btnFilter").click(function(){
		filterRecords();
	});
	
	// 导出按钮
	$("#btnExport").click(function(){
		popupExportDialog();
	});

	// 批量操作按钮
	$("#bthBatchUpdate").click(function(){
		popupBatchDialog();
	});

	// 初始化下个学期的资助记录
	$("#bthExtendFromPrevSemester").click(function(){
		extendFromPrevSemester();
	});
	
	// 录入资助记录
	$("#bthAddAidRecord").click(function(){
		popupAddAidDialog();
	});

	// 如果当前没有选中项目/学期，自动弹出对话框	
	var projectId = $("#selectedProjectId").val();
	var semesterId = $("#selectedSemesterId").val();
	if(projectId.length < 1 || semesterId.length < 1) {
		popupProjectPhaseDialog();
	}
});

function initFilters() {
	var urlBase = getAncestorPath(location.pathname, 2) + "public";
	//debugger
	fnAddSelectOption("#selectAidStatus", urlBase + "/student-aid-statuses");
	fnAddSelectOption("#selectAidType", urlBase + "/student-aid-types");
	fnAddSelectOption("#selectPairStatus", urlBase + "/student-pair-statuses");
	fnAddSelectOption("#selectFundStatus", urlBase + "/fund-statuses");
	fnAddSelectOption("#selectReceiptStatus", urlBase + "/student-feedback-statuses");
	fnAddSelectOption("#selectSummarytatus", urlBase + "/student-feedback-statuses");
	fnAddSelectOption("#selectReceiptFeedback", urlBase + "/sponsor-feedback-statuses");
	fnAddSelectOption("#selectSummaryFeedback", urlBase + "/sponsor-feedback-statuses");
}

function filterRecords(resetPhase) {
	if(resetPhase) {
		$("#page").val(1);
	}
	var projectId = $("#selectedProjectId").val();
	var semesterId = $("#selectedSemesterId").val();
	var limit = $("#limit").val();
	limit = (typeof limit == "undefined" || limit == null || limit == "") ? 20 : limit;
	var page = $("#page").val();
	page = (typeof page == "undefined" || page == null || page == "") ? 1 : page;
	var aidStatus = $("#selectAidStatus").val();
	var aidType = $("#selectAidType").val();
	var pairStatus = $("#selectPairStatus").val();
	var fundStatus = $("#selectFundStatus").val();
	var receiptStatus = $("#selectReceiptStatus").val();
	var summaryStatus = $("#selectSummarytatus").val();
	var receiptFeedbackStatus = $("#selectReceiptFeedback").val();
	var summaryFeedbackStatus = $("#selectSummaryFeedback").val();
	
	var url = getAncestorPath(location.pathname, 1);
	var postData = {projectId:projectId, semesterId:semesterId, page:page, limit:limit, aidStatus:aidStatus, aidType:aidType, pairStatus:pairStatus, fundStatus:fundStatus, receiptStatus:receiptStatus, summaryStatus:summaryStatus, receiptFeedbackStatus:receiptFeedbackStatus, summaryFeedbackStatus:summaryFeedbackStatus};
	
	$("#txtMessage").text("正在加载...")
    $.ajax({
        type: "GET",
        url: url,
        data: postData,
        success: function (resp) {
            if (resp.code == "0") {
                var tableBodyObj = $("#tableAidRecords tbody");
                tableBodyObj.html("");
                $.each(resp.data.rows,function(index, item) {
                	var jsonStr = JSON.stringify(item);
                	var rowHtml = "<tr dataStr=\'" + jsonStr + "\'>";
                	//debugger
                	rowHtml += "<td nowrap='nowrap'><input type='checkbox' name='aidIds' value='" + item.id +"'/>" + item.studentSn + "</td>";
                	rowHtml += "<td>" + item.studentName + "</td>";
                	rowHtml += "<td>" + item.studentGender + "</td>";
                	rowHtml += "<td>" + item.school + "</td>";
                	rowHtml += "<td>" + item.gradeName + "</td>";
                	rowHtml += "<td>" + item.aidStatusName + "</td>";
                	rowHtml += "<td>" + item.aidAmount + "</td>";
                	//rowHtml += "<td>" + item.fundStatusName + "</td>";
                	rowHtml += "<td>" + item.receiptStatusName + "</td>";
                	rowHtml += "<td>" + item.summaryStatusName + "</td>";
                	rowHtml += "<td>" + item.aidTypeName + "</td>";
                	rowHtml += "<td>" + item.sponsorName + "</td>";
                	rowHtml += "<td>" + item.pairStatusName + "</td>";
                	rowHtml += "<td>" + item.receiptFeedbackStatusName + "</td>";
                	rowHtml += "<td>" + item.summaryFeedbackStatusName + "</td>";
                	rowHtml += "<td>" + item.volunteerName + "</td>";
                	rowHtml += "<td>" + "<span class='clickable' onclick='popupAidDialog(event)'>Edit</span>" + "</td>";
                	rowHtml += "</tr>";
                	tableBodyObj.append(rowHtml);
                });
                
                var countSummaryObj = $("#txtCountSummary");
                countSummaryObj.html("共 " + resp.data.total + " 条记录，当前为第 " + resp.data.page + " 页");
                
                page = resp.data.page;
                //limit = resp.data.limit;
                $("#page").val(page);
                
                var navObj = $("#pagingNav");
                var urlBase = url + "?limit=" + limit;
                var navHtml = genPagingNavHtml(urlBase, resp.data.total, limit, page);
                //debugger
                navObj.html(navHtml);                

            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        	$("#txtMessage").text("");
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function navToPage(pageNumber) {
	$("#page").val(pageNumber);
	filterRecords();
}

//1.url pattern, 2.总记录数(resp.data.total)、每页多少行(limit)、当前第几页(page)
//以当前页为中心，前5页，后5页；判断最大最小边界
function genPagingNavHtml(urlBase, totalRows, pageSize, curPage) {
	var totalPages = Math.ceil(totalRows/pageSize);
	var step = 5;
	var min = curPage - 5;
	min = min<1 ? 1 : min;
	var max = min + 9;
	max = max>totalPages ? totalPages : max;

	var pagingHtml = "页码：";
	for(i=min; i<=max; i++) {
		if(i != curPage) {
			pagingHtml += "<span class='clickable' onclick='navToPage(" + i + ")'>" + i + "</span>";
		} else {
			pagingHtml += "<span>" + i + "</span>";
		}
	}
	
	return pagingHtml;
}

function extendFromPrevSemester() {
	var projectId = $("#selectedProjectId").val();
	var semesterId = $("#selectedSemesterId").val();
	var url = getAncestorPath(location.pathname, 1) + "extend_from_prev_semester?projectId=" + projectId + "&semesterId=" + semesterId;
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	alert(resp.message);
            	filterRecords();
            } else {
            	alert(resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });    	
}


var aidDialog = $("#aidDialog").dialog({
    autoOpen: false,
    height:430,
    width: 360,
    modal: true,
	close: function() {}
});

function initAidDialog() {
	var urlBase = getAncestorPath(location.pathname, 2) + "public";
	fnAddSelectOption("#aidDialog #aidStatus", urlBase + "/student-aid-statuses");
	fnAddSelectOption("#aidDialog #aidType", urlBase + "/student-aid-types");
	fnAddSelectOption("#aidDialog #pairStatus", urlBase + "/student-pair-statuses");
	fnAddSelectOption("#aidDialog #fundStatus", urlBase + "/fund-statuses");
	fnAddSelectOption("#aidDialog #receiptStatus", urlBase + "/student-feedback-statuses");
	fnAddSelectOption("#aidDialog #receiptFeedbackStatus", urlBase + "/sponsor-feedback-statuses");
	fnAddSelectOption("#aidDialog #summaryStatus", urlBase + "/student-feedback-statuses");
	fnAddSelectOption("#aidDialog #summaryFeedbackStatus", urlBase + "/sponsor-feedback-statuses");
	fnAddSelectOption("#aidDialog #grade", urlBase + "/grades");
	var url_sponsor_list = getAncestorPath(location.pathname, 2) + "sponsors/list_for_selection";
	fnAddSelectOption("#aidDialog #sponsorId", url_sponsor_list);
    var url_volunteer_list = getAncestorPath(location.pathname, 2) + "volunteers/list_for_selection";
    fnAddSelectOption("#aidDialog #volunteerId", url_volunteer_list);

	// init addAidDialog
	fnAddSelectOption("#addAidDialog #aidStatus", urlBase + "/student-aid-statuses");
	fnAddSelectOption("#addAidDialog #aidType", urlBase + "/student-aid-types");
	fnAddSelectOption("#addAidDialog #pairStatus", urlBase + "/student-pair-statuses");
	fnAddSelectOption("#addAidDialog #sponsorId", url_sponsor_list);

}

function popupAidDialog(event) {
	// 获取当前资助记录，初始化对话框
	event = event || window.event;
    var sourceObj = event.srcElement || event.target;
    var trObject = $(sourceObj).closest("tr");
    var item = JSON.parse(trObject.attr("dataStr"));
    //debugger
    $("#aidDialog #id").val(item.id);
    $("#aidDialog #studentInfo").text(item.studentName + "（" + item.studentSn + "）");
    $("#aidDialog #school").val(item.school);
    $("#aidDialog #grade").val(item.gradeId);
    $("#aidDialog #aidAmount").val(item.aidAmount);
    $("#aidDialog #aidStatus").val(item.aidStatus);
    $("#aidDialog #aidType").val(item.aidType);
    $("#aidDialog #pairStatus").val(item.pairStatus);
    $("#aidDialog #sponsorId").val(item.sponsorId);
    $("#aidDialog #volunteerId").val(item.volunteerId);
    $("#aidDialog #fundStatus").val(item.fundStatus);
    $("#aidDialog #receiptStatus").val(item.receiptStatus);
    $("#aidDialog #receiptFeedbackStatus").val(item.receiptFeedbackStatus);
    $("#aidDialog #summaryStatus").val(item.summaryStatus);
    $("#aidDialog #summaryFeedbackStatus").val(item.summaryFeedbackStatus);
    $("#aidDialog #remark").val(item.remark);
    
	aidDialog = aidDialog.dialog({
		label: "更新资助工作进展信息",
	    buttons: {
	    	"确定": updateStudentAid,
	    	Cancel: function() {
	    		aidDialog.dialog("close");
	    	}
	    }
	});
	aidDialog.dialog("open");
}

function updateStudentAid() {
	var school = $("#aidDialog #school").val();
	var gradeId = $("#aidDialog #grade").val();
	var aidAmount = $("#aidDialog #aidAmount").val();
	var aidStatus = $("#aidDialog #aidStatus").val();
	var aidType = $("#aidDialog #aidType").val();
	var pairStatus = $("#aidDialog #pairStatus").val();
	var sponsorId = $("#aidDialog #sponsorId").val();
    var volunteerId = $("#aidDialog #volunteerId").val();
	var fundStatus = $("#aidDialog #fundStatus").val();
	var receiptStatus = $("#aidDialog #receiptStatus").val();
	var receiptFeedbackStatus = $("#aidDialog #receiptFeedbackStatus").val();
	var summaryStatus = $("#aidDialog #summaryStatus").val();
	var summaryFeedbackStatus = $("#aidDialog #summaryFeedbackStatus").val();
	var remark = $("#aidDialog #remark").val();
	var postData = {school:school, gradeId:gradeId, aidAmount:aidAmount, aidStatus:aidStatus, aidType:aidType, pairStatus:pairStatus, sponsorId:sponsorId, volunteerId:volunteerId, fundStatus:fundStatus, receiptStatus:receiptStatus, receiptFeedbackStatus:receiptFeedbackStatus, summaryStatus:summaryStatus, summaryFeedbackStatus:summaryFeedbackStatus, remark:remark};
	var url = location.pathname + "/../" + $("#aidDialog #id").val();
	debugger

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	aidDialog.dialog("close");
            	filterRecords(); // 刷新页面                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });    
}

var addAidDialog = $("#addAidDialog").dialog({
    autoOpen: false,
    height:360,
    width: 360,
    modal: true,
	close: function() {}
});

// 从上学期接受资助的学生中，选中尚未生成本学期资助记录的学生，增加本学期的资助记录。
function popupAddAidDialog() {
	var selectedProject = $("#projectPhaseDialog #project option:selected");
	var projectId = selectedProject.val();
	$("#addAidDialog #projectId").val(projectId);
	$("#addAidDialog #projectName").text(selectedProject.text());
	$("#addAidDialog #sponsorId").val("");
	$("#addAidDialog #volunteerId").val("");
	$("#addAidDialog #school").val("");
	
	var urlBase = getAncestorPath(location.pathname, 2);
	
	if ($("#addAidDialog #semester option").length < 1) {
		var availableSemetserUrl = urlBase + "projects/" + projectId + "/phases";
		fnAddSelectOption("#addAidDialog #semester", availableSemetserUrl);
	}

	if($("#addAidDialog #grade option").length < 1) {
		fnAddSelectOption("#addAidDialog #grade", urlBase + "public/grades");
	}

	var semesterId = $("#selectedSemesterId").val();
	var studentsUrl = getAncestorPath(location.pathname, 1) + "unextended?projectId=" + projectId + "&semesterId=" + semesterId;
	$("#addAidDialog #student").empty();
	fnAddSelectOption("#addAidDialog #student", studentsUrl);

	
	addAidDialog = addAidDialog.dialog({
		label: "添加资助记录",
	    buttons: {
	    	"确定": addAidRecord,
	    	Cancel: function() {
	    		addAidDialog.dialog("close");
	    	}
	    }
	});
	addAidDialog.dialog("open");
}

function addAidRecord() {
	var studentId = $("#addAidDialog #student").val();
	var semesterId = $("#addAidDialog #semester").val();
	var projectId = $("#addAidDialog #projectId").val();
	var school = $("#addAidDialog #school").val();
	var gradeId = $("#addAidDialog #grade").val();
	var aidAmount = $("#addAidDialog #aidAmount").val();
	var aidStatus = $("#addAidDialog #aidStatus").val();
	var aidType = $("#addAidDialog #aidType").val();
	var pairStatus = $("#addAidDialog #pairStatus").val();
	var sponsorId = $("#addAidDialog #sponsorId").val();
	var volunteerId = $("#addAidDialog #volunteerId").val();
	var remark = $("#addAidDialog #remark").val();
	var url = getAncestorPath(location.pathname, 1);
	var postData = {studentId:studentId, semesterId:semesterId, projectId:projectId, school:school, gradeId:gradeId, aidAmount:aidAmount, aidStatus:aidStatus, aidType:aidType, pairStatus:pairStatus, sponsorId:sponsorId, volunteerId:volunteerId, remark:remark};
	debugger

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	addAidDialog.dialog("close");
            	filterRecords(); // 刷新页面                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

var exportDialog = $("#exportDialog").dialog({
    autoOpen: false,
    height:260,
    width: 360,
    modal: true,
	close: function() {}
});

function popupExportDialog() {
	debugger
	exportDialog = exportDialog.dialog({
		label: "下载助学跟踪信息",
	    buttons: {
	    	"导出": realExportAidData,
	    	Cancel: function() {
	    		exportDialog.dialog("close");
	    	}
	    }
	});
	exportDialog.dialog("open");	
}

function realExportAidData() {
	// export options
	var selectedOptions = $("#exportDialog input[name='exportOptions']:checked");
	var optionsValue = "";
	selectedOptions.each(function(){
		optionsValue += $(this).val() + ","
	});
	//alert(optionsValue);
		
	var projectId = $("#selectedProjectId").val();
	var semesterId = $("#selectedSemesterId").val();
	
	var url = getAncestorPath(location.pathname, 1);
	url += "export?projectId=" + projectId + "&semesterId=" + semesterId;
	url += "&options=" + optionsValue;
	//alert(url);
	location.href = url;
	
	exportDialog.dialog("close");
}

var batchDialog = $("#batchDialog").dialog({
    autoOpen: false,
    height:300,
    width: 300,
    modal: true,
    close: function() {}
});

function popupBatchDialog() {
	// get aidIds
    var idArray=new Array();
    $('input[name="aidIds"]:checked').each(function(){
        idArray.push($(this).val());
    });
    //var idstr=idArray.join(',');//将数组元素连接起来以构建一个字符串

    // if no aidIds checked, show alert.
    if(idArray.length==0) {
    	alert("您没有在当前页面选中学生。")
		return;
	}
    $("#batchDialog #aidIds").val(idArray);

    // show batch dialog
    batchDialog = batchDialog.dialog({
        label: "选中执行哪个操作",
        buttons: {
            "确定": batchUpdateAidRecord,
            Cancel: function() {
                batchDialog.dialog("close");
            }
        }
    });
    batchDialog.dialog("open");
}

function batchUpdateAidRecord() {
	var aidIds = $("#batchDialog #aidIds").val();
	var batchAction = $("#batchDialog input:radio[name='batchAction']:checked").val();
	if(!batchAction) {
		alert("请选择一个要执行的操作。")
		return;
	}

	var url = getAncestorPath(location.pathname, 1) + "batch_update?aidIds=" + aidIds + "&action=" + batchAction;
	$.ajax({
        type: "POST",
		url: url,
		dataType: "json",
		contentType:"application/json",
		success: function (resp) {
        	if (resp.code == "0") {
        		batchDialog.dialog("close");
        		filterRecords(); // 刷新页面
        	} else {
        		alert("服务器返回出错信息：\n\n" + resp.message);
        	}
        },
		error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
	});

}

function fnSelectAll(objCheckbox) {
	var selectAll = $(objCheckbox).is(":checked");
	if(selectAll) {
        $("input[name='aidIds']").prop("checked",true);
	}else {
        $("input[name='aidIds']").prop("checked",false);
	}
}